package com.example.demo.controller;

import com.example.demo.dto.CreateOrderRequest;
import com.example.demo.dto.OrderDTO;
import com.example.demo.dto.UpdateOrderStatusRequest;
import com.example.demo.enums.OrderStatusEnum;
import com.example.demo.enums.OrderTypeEnum;
import com.example.demo.enums.PaymentMethodEnum;
import com.example.demo.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 订单控制器
 * 
 * 演示功能：
 * 1. 枚举作为请求参数，框架自动转换
 * 2. 枚举作为响应数据，自动序列化为code值
 * 3. 参数验证和错误处理
 * 4. RESTful API设计
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@Validated
@Slf4j
@Api(tags = "订单管理", description = "订单相关的API接口")
public class OrderController {
    
    private final OrderService orderService;
    
    /**
     * 创建订单
     * 演示：接收JSON中的枚举code值，自动转换为枚举对象
     */
    @PostMapping
    @ApiOperation(value = "创建订单", notes = "创建新的订单，枚举字段传递code值即可")
    public ResponseEntity<OrderDTO> createOrder(
            @Valid @RequestBody @ApiParam("订单创建信息") CreateOrderRequest request) {
        
        log.info("创建订单请求：用户ID={}, 类型={}, 优先级={}, 支付方式={}", 
                request.getUserId(), 
                request.getType() != null ? request.getType().value() : null,
                request.getPriority() != null ? request.getPriority().value() : null,
                request.getPaymentMethod() != null ? request.getPaymentMethod().value() : null);
        
        OrderDTO order = orderService.createOrder(request);
        return ResponseEntity.ok(order);
    }
    
    /**
     * 根据ID查询订单
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询订单", notes = "返回的枚举字段为code值")
    public ResponseEntity<OrderDTO> getOrderById(
            @PathVariable @ApiParam("订单ID") Long id) {
        
        OrderDTO order = orderService.findById(id);
        return ResponseEntity.ok(order);
    }
    
    /**
     * 根据订单编号查询订单
     */
    @GetMapping("/by-order-no/{orderNo}")
    @ApiOperation(value = "根据订单编号查询订单")
    public ResponseEntity<OrderDTO> getOrderByOrderNo(
            @PathVariable @ApiParam("订单编号") String orderNo) {
        
        OrderDTO order = orderService.findByOrderNo(orderNo);
        return ResponseEntity.ok(order);
    }
    
    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/user/{userId}")
    @ApiOperation(value = "根据用户ID查询订单列表")
    public ResponseEntity<List<OrderDTO>> getOrdersByUserId(
            @PathVariable @ApiParam("用户ID") Long userId) {
        
        List<OrderDTO> orders = orderService.findByUserId(userId);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据订单状态分页查询
     * 演示：枚举作为请求参数，前端传递code值，自动转换为枚举对象
     */
    @GetMapping("/by-status")
    @ApiOperation(value = "根据订单状态分页查询", notes = "status参数传递枚举code值，如：1=待支付, 2=已支付")
    public ResponseEntity<Page<OrderDTO>> getOrdersByStatus(
            @RequestParam @ApiParam(value = "订单状态code值", example = "1") OrderStatusEnum status,
            @RequestParam(defaultValue = "0") @ApiParam("页码，从0开始") int page,
            @RequestParam(defaultValue = "10") @ApiParam("每页大小") int size) {
        
        log.info("根据状态查询订单：status={}, page={}, size={}", status.value(), page, size);
        
        Page<OrderDTO> orders = orderService.findByStatus(status, page, size);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据订单类型查询
     * 演示：枚举作为请求参数
     */
    @GetMapping("/by-type")
    @ApiOperation(value = "根据订单类型查询", notes = "type参数传递枚举code值，如：1=普通订单, 2=预售订单")
    public ResponseEntity<List<OrderDTO>> getOrdersByType(
            @RequestParam @ApiParam(value = "订单类型code值", example = "1") OrderTypeEnum type) {
        
        log.info("根据类型查询订单：type={}", type.value());
        
        List<OrderDTO> orders = orderService.findByType(type);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据支付方式查询
     * 演示：枚举作为请求参数
     */
    @GetMapping("/by-payment-method")
    @ApiOperation(value = "根据支付方式查询", notes = "paymentMethod参数传递枚举code值，如：1=支付宝, 2=微信支付")
    public ResponseEntity<List<OrderDTO>> getOrdersByPaymentMethod(
            @RequestParam @ApiParam(value = "支付方式code值", example = "1") PaymentMethodEnum paymentMethod) {
        
        log.info("根据支付方式查询订单：paymentMethod={}", paymentMethod.value());
        
        List<OrderDTO> orders = orderService.findByPaymentMethod(paymentMethod);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 更新订单状态
     * 演示：请求体中的枚举字段自动转换
     */
    @PutMapping("/{id}/status")
    @ApiOperation(value = "更新订单状态", notes = "status字段传递枚举code值")
    public ResponseEntity<OrderDTO> updateOrderStatus(
            @PathVariable @ApiParam("订单ID") Long id,
            @Valid @RequestBody @ApiParam("状态更新信息") UpdateOrderStatusRequest request) {
        
        log.info("更新订单状态：orderId={}, newStatus={}, reason={}", 
                id, request.getStatus().value(), request.getReason());
        
        OrderDTO order = orderService.updateStatus(id, request);
        return ResponseEntity.ok(order);
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    @ApiOperation(value = "取消订单")
    public ResponseEntity<OrderDTO> cancelOrder(
            @PathVariable @ApiParam("订单ID") Long id,
            @RequestParam(required = false) @ApiParam("取消原因") String reason) {
        
        log.info("取消订单：orderId={}, reason={}", id, reason);
        
        OrderDTO order = orderService.cancelOrder(id, reason != null ? reason : "用户取消");
        return ResponseEntity.ok(order);
    }
    
    /**
     * 获取待处理订单
     */
    @GetMapping("/pending")
    @ApiOperation(value = "获取待处理订单列表")
    public ResponseEntity<List<OrderDTO>> getPendingOrders() {
        List<OrderDTO> orders = orderService.findPendingOrders();
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 获取订单统计信息
     */
    @GetMapping("/statistics")
    @ApiOperation(value = "获取订单统计信息", notes = "按状态分组统计订单数量")
    public ResponseEntity<List<Object[]>> getOrderStatistics() {
        List<Object[]> statistics = orderService.getOrderStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 批量取消过期订单（管理员接口）
     */
    @PostMapping("/admin/cancel-expired")
    @ApiOperation(value = "批量取消过期订单", notes = "管理员接口，自动取消超时未支付的订单")
    public ResponseEntity<String> cancelExpiredOrders() {
        int cancelCount = orderService.cancelExpiredOrders();
        return ResponseEntity.ok("成功取消 " + cancelCount + " 个过期订单");
    }
}
